// product-list.js
import { products, checkLoginStatus, showMessage, formatPrice } from './utils.js';

// 加载商品列表
async function loadProducts(pageNum = 1, pageSize = 10, filters = {}) {
    const user = await checkLoginStatus();
    try {
        const response = await products.getByPage(pageNum, pageSize, filters);
        if (response.success) {
            renderProducts(response.data.items);
            renderPagination(response.data.totalPages, pageNum);
        } else {
            showMessage('error', '加载商品列表失败');
        }
    } catch (error) {
        showMessage('error', '加载商品列表失败');
    }
}

// 渲染商品列表
function renderProducts(products) {
    const productsContainer = document.getElementById('products-view');
    if (!productsContainer) return;

    productsContainer.innerHTML = '';

    products.forEach(product => {
        const productCard = document.createElement('div');
        productCard.className = 'product-card';
        productCard.innerHTML = `
            <div class="product-image">
                <img src="/uploads/products/${product.images?.[0] || 'default-product.jpg'}" alt="${product.name}">
            </div>
            <div class="product-info">
                <h3><a href="product-detail.html?id=${product.id}">${product.name}</a></h3>
                <div class="price">${formatPrice(product.price)}</div>
                <div class="seller">卖家: ${product.seller?.username || '未知'}</div>
            </div>
        `;
        productsContainer.appendChild(productCard);
    });
}

// 渲染分页
function renderPagination(totalPages, currentPage) {
    const pageNumbersContainer = document.getElementById('page-numbers');
    if (!pageNumbersContainer) return;

    pageNumbersContainer.innerHTML = '';

    for (let i = 1; i <= totalPages; i++) {
        const pageNumber = document.createElement('button');
        pageNumber.className = `page-number ${i === currentPage ? 'active' : ''}`;
        pageNumber.textContent = i;
        pageNumber.addEventListener('click', () => {
            loadProducts(i);
        });
        pageNumbersContainer.appendChild(pageNumber);
    }
}

// 页面加载时执行
document.addEventListener('DOMContentLoaded', () => {
    loadProducts();
});